# store
from redis import StrictRedis
from requests import Session
import requests
from flask import Flask
import random
import time
import re
from multiprocessing import Process
from threading import Thread


url = 'https://antispider6.scrape.center/login'
url_center = 'https://antispider6.scrape.center/'
db = StrictRedis(host='localhost', port=6379, db=0,
                 decode_responses=True)
s = Session()
app = Flask(__name__)

# for username, cookie in db.hgetall('account').items():
#     if int(re.search(r'admin(.+)', username).group(1)) >= 10:
#         print(int(re.search(r'admin(.+)', username).group(1)))
#         db.hdel('account', username)


def Getcookie():  # 没有cookie就获取cookie并填入
    while True:
        for username in db.hkeys('account'):
            if not db.hexists('cookie', username):
                r = s.post(url=url, data={'username': username,
                                          'password': db.hget('account', username)})
                result = []
                for cookie in s.cookies:
                    result.append(f'{cookie.name}={cookie.value}')
                result = ';'.join(result)
                db.hset('cookie', username, result)
                print('cookie', username, result)
        time.sleep(10)


def Testcookie():  # 根据res状态码把库中cookie无效的username键值对删除
    while True:
        for username, cookie in db.hgetall('cookie').items():
            res = requests.get(
                url_center, headers={'Cookie': cookie}, allow_redirects=True)
            # print(res.status_code, res.text)
            if res.status_code != 200:
                db.hdel('cookie', username)
                print('cookie', username, res.status_code, '已失效！')
            print('cookie', username, res.status_code, '可用！')
        time.sleep(10)


@app.route('/')  # 接口功能
def cookie_api():
    result = db.hvals('cookie')
    result = random.choice(result)
    return result


def api():
    app.run()


def schedule():
    p1 = Process(target=Getcookie)
    p2 = Process(target=Testcookie)
    p3 = Process(target=api)
    p1.start()
    p2.start()
    p3.start()
    p1.join()
    p2.join()
    p3.join()


if __name__ == '__main__':
    schedule()
